package com.example.griddemo.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.griddemo.R;
import com.example.griddemo.adapter.CategoryTabsAdapter;
import com.example.griddemo.adapter.GoodsListAdapter;
import com.example.griddemo.api.ApiService;
import com.example.griddemo.interfaces.ResponseCallback;
import com.example.griddemo.viewmodel.Category;
import com.example.griddemo.viewmodel.CategoryDetail;
import com.example.griddemo.viewmodel.Goods;
import com.example.griddemo.viewmodel.GoodsListResponse;
import com.example.griddemo.viewmodel.ResponseData;

import java.util.ArrayList;
import java.util.List;

public class GoodsListActivity extends AppCompatActivity {

    private ImageView ivBack;
    private RecyclerView rvCategoryTabs;
    private TextView tvCategoryTitle;
    private TextView tvCategoryDesc;
    private RecyclerView rvGoodsList;
    private ProgressBar progressBar;
    private LinearLayout llEmptyView;

    private int currentCategoryId;
    private List<Category> brotherCategories = new ArrayList<>();
    private List<Goods> goodsList = new ArrayList<>();
    private CategoryTabsAdapter tabsAdapter;
    private GoodsListAdapter goodsAdapter;

    private int currentPage = 1;
    private final int pageSize = 10;
    private boolean isLoading = false;
    private boolean isLastPage = false;
    private long lastClickTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);

        initViews();
        initData();
    }

    private void initViews() {
        ivBack = findViewById(R.id.iv_back);
        rvCategoryTabs = findViewById(R.id.rv_category_tabs);
        tvCategoryTitle = findViewById(R.id.tv_category_title);
        tvCategoryDesc = findViewById(R.id.tv_category_desc);
        rvGoodsList = findViewById(R.id.rv_goods_list);
        progressBar = findViewById(R.id.progress_bar);
        llEmptyView = findViewById(R.id.ll_empty_view);

        ivBack.setOnClickListener(v -> finish());

        // 分类标签
        rvCategoryTabs.setLayoutManager(new LinearLayoutManager(
                this, LinearLayoutManager.HORIZONTAL, false));
        tabsAdapter = new CategoryTabsAdapter(brotherCategories);
        tabsAdapter.setOnTabClickListener(category -> {
            if (System.currentTimeMillis() - lastClickTime < 500) return;
            lastClickTime = System.currentTimeMillis();

            if (category.getId() == currentCategoryId) return;

            currentCategoryId = category.getId();
            currentPage = 1;
            isLastPage = false;

            // 更新标题和描述
            updateTitleAndDesc(category);

            loadGoodsList(true);
        });
        rvCategoryTabs.setAdapter(tabsAdapter);

        // 商品列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvGoodsList.setLayoutManager(layoutManager);
        goodsAdapter = new GoodsListAdapter(goodsList);
        rvGoodsList.setAdapter(goodsAdapter);

        // 滚动监听
        rvGoodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if (!isLoading && !isLastPage && dy > 0) {
                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                            && firstVisibleItemPosition >= 0
                            && totalItemCount >= pageSize) {
                        loadGoodsList(false);
                    }
                }
            }
        });
    }

    private void initData() {
        currentCategoryId = getIntent().getIntExtra("categoryId", -1);
        if (currentCategoryId == -1) {
            showToast("无效的分类ID");
            finish();
            return;
        }

        loadCategoryData();
        loadGoodsList(true);
    }

    private void loadCategoryData() {
        ApiService.getCategoryDetail(currentCategoryId, new ResponseCallback<ResponseData<CategoryDetail>>() {
            @Override
            public void onSuccess(ResponseData<CategoryDetail> response) {
                if (response == null || response.getData() == null) {
                    showToast("分类数据为空");
                    return;
                }

                CategoryDetail data = response.getData();
                updateCategoryUI(data);
            }

            @Override
            public void onError(String error) {
                showToast("加载分类失败: " + error);
                new Handler().postDelayed(() -> loadCategoryData(), 2000);
            }
        });
    }

    private void updateCategoryUI(CategoryDetail data) {
        if (data.getCurrentCategory() != null) {
            updateTitleAndDesc(data.getCurrentCategory());
        }

        if (data.getBrotherCategory() != null && !data.getBrotherCategory().isEmpty()) {
            brotherCategories.clear();
            brotherCategories.addAll(data.getBrotherCategory());
            tabsAdapter.notifyDataSetChanged();
            selectCurrentCategory();
        }
    }

    private void updateTitleAndDesc(Category category) {
        tvCategoryTitle.setText(category.getName());
        tvCategoryDesc.setText(category.getDesc());
    }

    private void selectCurrentCategory() {
        for (int i = 0; i < brotherCategories.size(); i++) {
            if (brotherCategories.get(i).getId() == currentCategoryId) {
                tabsAdapter.setSelectedPosition(i);
                rvCategoryTabs.smoothScrollToPosition(i);
                break;
            }
        }
    }

    private void loadGoodsList(boolean isRefresh) {
        if (isLoading) return;

        isLoading = true;
        if (isRefresh) {
            progressBar.setVisibility(View.VISIBLE);
            llEmptyView.setVisibility(View.GONE);
        }

        ApiService.getGoodsList(currentCategoryId, currentPage, pageSize,
                new ResponseCallback<ResponseData<GoodsListResponse>>() {
                    @Override
                    public void onSuccess(ResponseData<GoodsListResponse> response) {
                        isLoading = false;
                        progressBar.setVisibility(View.GONE);

                        if (response == null || response.getData() == null) {
                            showEmptyView();
                            return;
                        }

                        GoodsListResponse data = response.getData();
                        updateGoodsList(data, isRefresh);
                    }

                    @Override
                    public void onError(String error) {
                        isLoading = false;
                        progressBar.setVisibility(View.GONE);
                        showToast("加载失败: " + error);

                        if (isRefresh) {
                            showEmptyView();
                        }
                    }
                });
    }

    private void updateGoodsList(GoodsListResponse data, boolean isRefresh) {
        if (isRefresh) {
            goodsList.clear();
        }

        if (data.getList() != null && !data.getList().isEmpty()) {
            goodsList.addAll(data.getList());
            goodsAdapter.notifyDataSetChanged();

            isLastPage = data.getPage() >= data.getPages();

            if (!isRefresh && !isLastPage) {
                currentPage++;
            }

            llEmptyView.setVisibility(View.GONE);
        } else {
            showEmptyView();
        }
    }

    private void showEmptyView() {
        if (goodsList.isEmpty()) {
            llEmptyView.setVisibility(View.VISIBLE);
        } else {
            llEmptyView.setVisibility(View.GONE);
        }
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }
}